%% First load data arrays for analysis
clear;
fnames = dir("monod*.mat");
for k=1:length(fnames)
    load(fnames(k).name);
end


clc;
close all;

%% Establish concentrations to evaluate
ivec = [1:5]'; % Only use first 4 concentrations

%% Define molar mass
% Define approximate molar mass of components
molmass_yeastextract = 274; % g/L
molmass_tryptone = 71;

% Total carbon molar mass
molmass_LB = 5/molmass_yeastextract + 10/molmass_tryptone;

tempmat = monod_mat_LB_37C;
concentration = tempmat(:,1)/100*molmass_LB*1000; % Convert to mM

%% 37C LB
tempmat = monod_mat_LB_25C;
smat = size(tempmat);


grmax_25C = nanmean(tempmat(ivec,2:4),2);
grmax_err_25C = nanstd(tempmat(ivec,2:4),0,2);

%% 30C LB
tempmat = monod_mat_LB_30C;
smat = size(tempmat);


grmax_30C = nanmean(tempmat(ivec,2:4),2);
grmax_err_30C = nanstd(tempmat(ivec,2:4),0,2);

%% 37C LB
tempmat = monod_mat_LB_37C;
smat = size(tempmat);


grmax_37C = nanmean(tempmat(ivec,2:4),2);
grmax_err_37C = nanstd(tempmat(ivec,2:4),0,2);

%% Now do Arrhenius analysis
T = [25 30 37]';
clrs = distinguishable_colors(length(ivec));

grmax_tot_LB = [grmax_25C grmax_30C grmax_37C];
grmax_err_tot_LB = [grmax_err_25C grmax_err_30C grmax_err_37C];

Ea_LB = [];
Ea_err_LB = [];

figure;
for k=1:length(ivec)
    g = grmax_tot_LB(k,:)';
    ge = grmax_err_tot_LB(k,:)';
%     [f1,f2] = fit(1./(T+273.15), log(g),'poly1', 'Weights', 1./((ge./g).^2));
    [f1,f2] = unfolding_Arrhenius_weighted_fit(T+273.15, g,ge);

    clr = clrs(k,:);

    errorbar(1./(T+273.15), log(g), ge./g, 'o', 'linewidth', 1, 'color', clr);
    hold on;
    plot(1./(T+273.15),log(f1(T+273.15)), 'color', clr , 'linewidth', 1);
    disp('Activation Energy (KT):');
    disp(-f1.p1/298);
    
    disp('With error:');
    
    alpha = 0.90;
    ci = confint(f1, alpha);
    fiterr = abs(f1.p1 - ci(1,1))/298;
    disp(fiterr);
    
    Ea_LB = [Ea_LB; -f1.p1/298];
    Ea_err_LB = [Ea_err_LB; fiterr];
    
    
end

set(gca, 'fontsize', 20);
set(gcf, 'Position', [0 0 400 300]);
xlabel('1/T (1/K)');
ylabel('Log (growth rate)');
xlim([1/312 1/296]);

%% Plot Ea vs. concentration (in units of kcal/mol)
figure;
errorbar(log(concentration), Ea_LB/1.688, Ea_err_LB/1.688, 'bo');
ylim([0 40]);
set(gca, 'fontsize', 20);
set(gcf, 'Position', [0 0 400 300]);
xlabel('Log(concentration)');
ylabel('Activation energy (kcal/mol)');
box off
% xlim([0 max(concentration)*1.1])

%% Compute average activation energy at saturation, with standard error
sat_index = [1:2]; % Indexing for saturating concentrations

Ea_mean = mean(Ea_LB(sat_index))/1.688
Ea_mean_err = sqrt(sum(Ea_err_LB(sat_index).^2)/length(sat_index))/1.688
% Ea_se = Ea_mean_err/sqrt(length(sat_index));









